package san.java.day12;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * 文件字节流
 *  文件字节流非常通用, 可以用来操作字符的文档,还可以操作任何其他类型文件
 *  因为字节流使用的是二进制
 *
 */

public class FileByteStream_05 {

    private static void testInput() {
        try {
            FileInputStream in = new FileInputStream("data/a1.txt");
            // 设置一个byte数组接受读取的文件的内容
            byte[] b = new byte[10];

            int len = 0;
            while ((len = in.read(b)) != -1) {
                System.out.println(new String(b, 0, len));
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void testOutput() {
        try {
            FileOutputStream out = new FileOutputStream("data/a2.txt");
            String str = "hkjbsadbaskfna";
            out.write(str.getBytes());
            out.flush();  // 刷新缓冲区

            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void copyFile(File src, File dest) throws Exception {
        if (!src.exists())
            throw new RuntimeException("源文件不存在");

        if (!dest.exists()) {
            throw new Exception("目标路径不存在");
        }

        String path = "";
        if (dest.isFile()) {
            path = dest.getAbsolutePath();
        } else if (dest.isDirectory()){
            path = dest.getAbsoluteFile() + "/" + src.getName();
        }


        File temp = new File(path);
        if (!temp.exists()) {
            temp.createNewFile();
        }

        FileOutputStream out = new FileOutputStream(temp);
        FileInputStream in = new FileInputStream(src);
        byte[] bytes = new byte[50];
        int len = 0;

        while ((len = in.read(bytes)) != -1) {
            out.write(bytes, 0, len);
            out.flush();
        }
        out.close();
    }

    public static void main(String[] args) {
        testOutput();
        File src = new File("data/a2.txt");
        File dest = new File("data/test/a3.txt");
        try {
            copyFile(src, dest);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        File src = new File("data/a1.txt");
//        File dest = new File("data");
//        System.out.println(src.exists());
        System.out.println(src.getName());
        System.out.println(dest.getAbsolutePath() + "/" + src.getName());
    }

}
